<template>
  <el-button type="primary" @click="add">添加用户</el-button>
  <el-dialog title="用户" v-model="dialogFormVisible" :before-close="clear">
    <el-form :model="form" :rules="rules" ref="userForm">
      <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
        <el-input v-model.number="form.age" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
        <el-input v-model.number="form.phone" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
        <el-input v-model="form.password" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" :label-width="formLabelWidth" prop="repassword">
        <el-input v-model="form.repassword" auto-complete="off"></el-input>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="clear">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import {ref} from "vue";

const dialogFormVisible = ref(false) // 对话框是否显示
const form = ref({})
const userForm = ref()
const formLabelWidth = ref('100px') // 宽度
// todo: 验证规则
const rules = ref({
  name:[
    {required:true,message:'请输入姓名',trigger:'blur'},
    {min:1,max:5,message:'长度在1到5之间',trigger:'blur'}
  ],
  age:[
    {required:true,message:'请输入年龄',trigger:'blur'},
    {type:'number',min:1,max:100,message:'年龄在1到100之间',trigger:'blur'}
  ],
  phone:[
    {required:true,message:'请输入手机号',trigger:'blur'},
    {pattern:/^1[35789]\d{9}$/, message:'手机号格式不正确',trigger:'blur'}
  ],
  password:[
    {required:true,message:'请输入密码',trigger:'blur'},
    {min:1,max:5,message:'长度在1到5个字符',trigger:'blur'}
  ],
  repassword:[
      {required:true,message:'请输入确认密码',trigger:'blur'},
      {min:1,max:5,message:'长度在1到5之间',trigger:'blur'},
    {validator:(rule,value,callback)=>{
      if (value !== form.value.password){
        callback(new Error('两次密码不一致'))
      }else{
        callback()//就算验证成功,有需要callback
      }
}}]
})

const add = () => {
  dialogFormVisible.value = true
}

const clear = () => {
}

const save = () => {
  userForm.value.validate(valid => {
  if (!valid){
    alert('验证未通过')
  }else{
    alert('验证通过')
  }
  })
}
</script>

<style scoped>

</style>